import type {ResponseData, ResponsePaginationData} from '@/utils/request';
import {SUCCESS_CODE} from '@/utils/request';
import type {RequestData} from '@ant-design/pro-table';
import {message} from 'antd';
import type {
  CreationItem,
  DetailItem,
  DeviceBindRequestModel,
  EditItem,
  QueryItem,
  TableListItem
} from './data';
import {request} from 'umi';

export {queryZoneList} from '../Zones/service';

type Pagination = { page?: number; pageSize?: number };

/**
 * 获取指定泊位详细信息
 * @param spaceId
 */
export async function querySpaceDetail(spaceId: string): Promise<{
  success: boolean;
  data?: DetailItem;
}> {
  const res = await request(`/spaces/space/${spaceId}/details`);
  if (!res || res.code !== SUCCESS_CODE) {
    return {success: false};
  }

  return {
    success: true,
    data: {
      ...res.data,
      id: res.data.id,
      spaceName: res.data.spaceName,
      zone: {
        id: res.data.zoneId,
        name: res.data.zoneName,
        no: res.data.zone?.zoneNo || '',
      },
      device: {
        id: res.data.bindDevice,
        deviceName: res.data.bindDevice,
        deviceType: 'lock',
        deviceNo: res.data.bindDevice,
      },
      plateNumber: res.data.plateNumber,
      deviceNo: res.data.bindDevice,
    },
  };
}

/**
 * 获取泊位列表
 * @param params
 */
export async function querySpaceList(
    params: Pagination & QueryItem,
): Promise<RequestData<TableListItem>> {
  const res: ResponsePaginationData<any> = await request('/spaces/space/list', {
    params: {
      page: params.page,
      pageSize: params.pageSize,
      spaceName: params.spaceName,
      zone: params.zone?.id,
      type: params.type,
    },
  });
  if (!res || res.code !== SUCCESS_CODE) {
    message.error('获取失败');
    return {success: false, total: 0, data: []};
  }
  return {
    success: true,
    total: res.data.total,
    data: res.data.list.map(item => ({
      ...item,
      id: item.id,
      plateNumber: item.plateNumber,
      spaceName: item.spaceName,
      location: [item.lng, item.lat],
      status: String(item.status),
      zone: {
        id: item.zoneId,
        name: item.zoneName || '',
      },
      address: '',
      deviceNo: item.bindDevice,
      device: item.bindDevice
          ? {
            id: item.bindDevice,
            deviceName: item.bindDevice,
            deviceNo: item.bindDevice,
            deviceType: 'lock',
          }
          : undefined,
    })),
  };
}

/**
 * 添加泊位
 * @param params
 */
export async function addSpace(params: CreationItem) {
  const res: ResponseData<any> = await request('/spaces/space/create', {
    method: 'POST',
    data: {
      ...params,
      address: params.address,
      lng: params.location?.[0],
      lat: params.location?.[1],
      spaceName: params.spaceName,
      zoneId: params.zone.id,
      deviceNo: params.deviceNo,
      ownerId: params.owner?.id,
    },
  });
  return res;
}

export interface SpaceOwnerInfo {
  idCard: string;
  name: string;
  img: string;
  phone: string;
  id: string;
  deviceNo: string;
  zone: {
    id: string;
  };
  spaceName: string;
  owner: { id: string; name: string };
}

/**
 * 更新泊位所有者信息
 * @param params
 */
export async function updateSpaceOwnerInfo(data: SpaceOwnerInfo) {
  const res: ResponseData<any> = await request(`/spaces/space/${data.id}`, {
    method: 'PUT',
    data: {...data, ownerId: data.owner?.id},
  });
  return res;
}

export async function editSpace(params: EditItem) {
  if (!params.id || !params.spaceName) return undefined;
  return request(`/spaces/space/${params.id}`, {
    method: 'POST',
    data: {
      spaceName: params.spaceName,
    },
  });
}

/**
 * 绑定设备
 * @param params
 */
export async function bindDevice(params: DeviceBindRequestModel): Promise<any> {
  const res: ResponseData<any> = await request('/spaces/space/bindDevice', {
    method: 'POST',
    data: {
      spaceId: params.spaceId,
      deviceNo: params.deviceNo,
    },
  });

  if (res.code !== SUCCESS_CODE) {
    message.error(res.message);
    return undefined;
  }

  return true;
}

/**
 * 解绑设备
 * @param params
 */
export async function unbindDevice(params: { deviceNo: string; zoneId: string }) {
  return request('/spaces/space/unbindDevice', {
    method: 'POST',
    data: {deviceId: params.deviceNo, spaceId: params.zoneId},
  });
}

/**
 * 删除泊位
 * @param params
 */
export async function removeSpace(params: { id: string }): Promise<void> {
  const res: ResponseData<any> = await request(`/spaces/space/${params.id}`, {method: 'DELETE'});

  if (res.code !== SUCCESS_CODE) {
    throw new Error(res.message);
  }
}

/**
 * 更新泊位开锁授权
 * @param params
 */
export async function updateSpaceUnlockAuth(params: { spaceId: string; userIdentifies: string[] }) {
  const res = await request('/space/unlock/authorization/resetSpaceUnlockAuth', {
    method: 'POST',
    data: {spaceId: params.spaceId, userIdentifies: params.userIdentifies},
  });
  if (res.code !== SUCCESS_CODE) {
    return {success: false, message: res.message};
  }
  return {success: true, message: 'success'};
}

export interface OwnerSelectionItem {
  name: string;
  id: string;
}

export async function findMatchOwnerList(
    params: Pagination & { name?: string; type: number },
): Promise<RequestData<OwnerSelectionItem>> {
  const {name, type: ownerType} = params;
  const res: ResponsePaginationData<any> = await request('/owner/matcher-list', {
    params: {page: 1, pageSize: 20, name, ownerType},
  });
  if (res?.code !== SUCCESS_CODE) {
    return {success: false, total: 0, data: []};
  }

  return {
    success: true,
    total: res.data.total,
    data: res.data.list.map(item => ({
      name: `${item.name}(${item.phone})`,
      id: item.id,
    })),
  };
}
